package com.pug.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.pug.user.dto.DeductionReqDTO;
import com.pug.user.dto.DeductionRespDTO;
import com.pug.user.mapper.UserMapper;
import com.pug.user.po.UserPO;
import com.pug.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xq.pug.common.exception.ServiceException;
import xq.pug.feign.dto.user.UserFeignReqDTO;
import xq.pug.feign.dto.user.UserFeignRespDTO;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @program: xq_pug_alibabacloud_parent
 * @description:
 * @author: Mr.Ren
 * @create: 2023-04-16 15:36
 **/
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserFeignRespDTO queryUser(UserFeignReqDTO dto) {
        UserPO queryPO = BeanUtil.copyProperties(dto, UserPO.class);
        UserPO po = userMapper.queryUser(queryPO);
        return BeanUtil.copyProperties(po, UserFeignRespDTO.class);
    }

    @Override
    public DeductionRespDTO deduction(DeductionReqDTO dto) {
        //查询该用户
        UserPO userPO = userMapper.queryByUserCode(dto.getUserCode());
        if (Objects.isNull(userPO)) {
            log.error("未查询到该用户的信息，请检查。userCode:{}", dto.getUserCode());
            throw new ServiceException("未查询到该用户的信息，请检查。userCode:" + dto.getUserCode());
        }
        BigDecimal totalPrice = dto.getPrice().multiply(new BigDecimal(dto.getNum()));
        BigDecimal remaining = userPO.getAmount().subtract(totalPrice);
        if (remaining.compareTo(BigDecimal.ZERO) < 0) {
            log.error("该用户余额不足已支付该笔订单，请检查。userCode:{}", dto.getUserCode());
            throw new ServiceException("该用户余额不足已支付该笔订单，请检查。userCode:" + dto.getUserCode());
        }

//        userPO.setUpdateTime(new Date());
//        userPO.setAmount(remaining);
//        userMapper.updateUser(userPO);
        userMapper.updateAmount(dto.getUserCode(),remaining);
        log.info("消费成功");
        DeductionRespDTO respDTO = new DeductionRespDTO();
        respDTO.setUserCode(dto.getUserCode());
        respDTO.setConsumerPrice(totalPrice);
        return respDTO;
    }
}
